package com.fengxun.software_cup.util;
// 团   队: 风讯网络
// 后   端: Dopa
// 开发时间: 2021/6/14 22:43

import com.fengxun.software_cup.mapper.UserMapper;
import com.fengxun.software_cup.pojo.CommonResult;
import com.fengxun.software_cup.pojo.Sent_mean;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.Base64;



@Component
public class CommonUtil {
    /**
     * 以流的方式读取图片并返回其Base64编码
     * @param image 图片
     * @return 图片BASE64编码
     */
    public static String getImageBase(MultipartFile image) throws IOException {
        InputStream in = image.getInputStream();
        byte[] data = new byte[in.available()];
        in.read(data);

        in.close();
        return Base64.getEncoder().encodeToString(data);
    }

    /**
     * 调用python模块
     * @param python_path python模块路径
     * @param file_path python处理文件路径
     * @return 执行结果
     * @throws IOException io异常
     * @throws InterruptedException 中断异常
     */
    public static int transferPython(String python_path, String file_path) throws IOException, InterruptedException {
        Process proc;
        String[] args1 = new String[]{"python", python_path, file_path};
        proc = Runtime.getRuntime().exec(args1);
        return proc.waitFor();
    }


    /**
     * state==1,则返回Sent_mean
     * @param mapper 持久层对象
     * @param state 状态码（区别文件和图片）
     * @return
     */
    public static CommonResult<Object> getResult(UserMapper mapper,int state){

        if (state==0){
            return new CommonResult<>(200, "success");
        }
        Sent_mean[] mean = mapper.getSent_mean();
        if (mean == null) {
            return new CommonResult<>(500, "Query failed");
        }
        return new CommonResult<>(200, "success", mean);
    }


}
